package com.fengxing.ams.web.facade.mouble.student;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import redis.clients.jedis.Jedis;

import com.fengxing.ams.web.common.SerializeUtil;
import com.fengxing.ams.web.facade.mouble.BaseRedis;

@Repository
public class StudentRedis extends BaseRedis implements IStudentRedis {

	private static final String[] fields = new String[]{"subject","batch","year","student_id","student_name","student_nation","student_gendar","apply_score","test_score","college_id","college_code","college_name","major_id","major_name","major_code","enrolled_type","single_score","description_id","location"};
	
	@Override
	public List<StudentVO> getStudentByKey(String buildKey) {
		Jedis jedis = this.getJedis();
		
		List<StudentVO> students = new ArrayList<StudentVO> ();
		try {
			Set<byte[]> cacheResult = jedis.zrangeByScore((ENROLL_STUDENTS+buildKey).getBytes("UTF-8"), -1, 1);
			if (cacheResult == null || cacheResult.isEmpty()) {
				return null;
			}
			for (byte[] data : cacheResult) {
				students.add((StudentVO)SerializeUtil.unserialize(data));
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			this.closeJedis(jedis);
		}
		return students;
	}

	@Override
	public void setStudentByKey(String buildKey, List<StudentVO> students) {
		if (students == null || students.isEmpty())
			return;
		Jedis jedis = this.getJedis();
		
		try {
			Map<byte[], Double> map = buildMap(students);
			jedis.zadd((ENROLL_STUDENTS+buildKey).getBytes("UTF-8"), map);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			this.closeJedis(jedis);
		}
	}
	
	private Map<byte[], Double> buildMap(List<StudentVO> students) {
		Map<byte[], Double> map = new HashMap<byte[], Double> ();
		for (StudentVO vo : students) {
			map.put(SerializeUtil.serialize(vo), 0.0);
		}
		return map;
	}
	
}
